#include "HCHOsensor.h"

HCHOSensor::HCHOSensor(int rxPin,int txPin)
{
    p_serial = new SoftwareSerial(rxPin,txPin);
    p_serial->begin(9600);
    //p_serial->println("hello new SoftwateSerial!");
}

HCHOSensor::~HCHOSensor()
{
    p_serial->~SoftwareSerial();
}

bool HCHOSensor::getValue()
{
    Cmd_Send(CMD_QUERY,0);
    uint8_t rBuffer[10];
    
    p_serial->readBytes(rBuffer,10);
    //捕捉帧头
    if(rBuffer[0]==FRAME_HEAD1 && rBuffer[1]==FRAME_HEAD2)
    {
        //判断校验位
        if(rBuffer[9] ==  check_sum(rBuffer,9))
        {
            VH = rBuffer[5]; //当量值
            Data16 = (rBuffer[6]<<8) + rBuffer[7];
            HCHO_Value =(float)Data16/pow(10,VH-1);
            return true;
        }
    }
    return false;
}

void HCHOSensor::Cmd_Send(uint8_t cmd,uint16_t cmdData)
{
    uint8_t f_data[7];
    uint16_t crc16=0;
    f_data[0] = FRAME_HEAD1;
    f_data[1] = FRAME_HEAD2;
    f_data[2] = cmd;
    f_data[3] = cmdData>>8;
    f_data[4] = cmdData;
    crc16 = check_sum(f_data,5);
    f_data[5] = crc16>>8;
    f_data[6] = crc16;
    p_serial->write(f_data,7);
  
}

uint16_t HCHOSensor::check_sum(uint8_t *buf,uint16_t length)
{
    uint16_t sum = 0;
    for(uint16_t i=0;i<length;i++)
    {
        sum+=buf[i];
    } 
    return sum;
}